package pub.gll.onepeas.libbase.track.util

import androidx.collection.ArrayMap
import pub.gll.onepeas.libbase.track.model.ExposureModel


/**
 * <pre>
 *     @author : whg
 *     @e-mail : guanhuawei@kkworld.com
 *     @time   : 2021/6/23 11:06
 *     @desc   : 内部工具类
 *     @version: 1.0
 * </pre>
 */
object ExposureDataManager {


    private var commitLogs: MutableMap<Any, Int> = ArrayMap()

    /**
     * 计算并且获取当前view曝光的次数，view可见时次数增加
     * @param model ExposureModel?
     * @return Int
     */
    private fun getExposureTimes(model: ExposureModel?, needAdd: Boolean): Int {
        if (needAdd) {
            caculateExposureTimes(model)
        }
        return commitLogs[model?.tag] ?: 1
    }

    /**
     * 计算view曝光的次数
     * @param model ExposureModel?
     */
    private fun caculateExposureTimes(model: ExposureModel?) {
        model?.tag?.let { tag ->
            if (!commitLogs.containsKey(tag)) {
                commitLogs.put(tag, 1)
            } else {
                commitLogs[tag]?.let { count ->
                    var curCount = count
                    commitLogs.put(tag, ++curCount)
                }
            }
        }
    }


    /**
     * check the exposure duration
     *
     * @param model
     * @return
     */
    private fun getExposureViewDuration(model: ExposureModel?): Long {
        if (model == null) return 0
        if (model.beginTime > 0 && model.endTime > 0 && model.endTime > model.beginTime) {
            val duration = model.endTime - model.beginTime
            //真实有效曝光时间
            if (duration < 2 * 60 * 60 * 1000) {
                return duration
            }
        }
        return 0
    }

    /**
     * view消失时机
     * @param model ExposureModel?
     */
    fun onViewInVisible(model: ExposureModel?) {
        model?.let {
            it.endTime = System.currentTimeMillis()
            var duration = getExposureViewDuration(it)
            if (duration > 0) {
                var exposureTime = getExposureTimes(it, false)
                it.listener?.onViewInVisible(it.view, exposureTime, duration, it.params)
                it.recycleUnchecked()
            }
        }
    }

    /**
     * view曝光时机
     * @param model ExposureModel?
     */
    fun onViewVisible(model: ExposureModel?) {
        model?.let {
            it.endTime = System.currentTimeMillis()
            var exposureTime = getExposureTimes(it, true)
            it.listener?.onViewVisible(it.view, exposureTime, it.params)
            it.recycleUnchecked()
        }
    }

}